package cn.wolfcode.exception;

import cn.wolfcode.domain.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对控制器进行增强
 */
@ControllerAdvice
public class MyControllerAdvice {
    @ExceptionHandler(RuntimeException.class)
    public String handler(RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod){
        e.printStackTrace();
        //判断是否有贴注解
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult jsonResult = new JsonResult(false, "系统异常,请联系管理员");
            try {
                //设置响应格式
                response.setContentType("appplication/json;charset=utf-8");
                //响应json字符串
                response.getWriter().write(JSON.toJSONString(jsonResult));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }else {
            return "/common/error";
        }
        return null;
    }

    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public JsonResult logicExceptionHandler(RuntimeException e){
        e.printStackTrace();
        return new JsonResult(false, e.getMessage());
    }
}
